/**
 * com.future CO.,ltd.
 */

package com.future;


import java.util.Arrays;

/**
 * 给你一个整数数组nums 以及两个整数lower 和 upper 。求数组中，值位于范围 [lower, upper] （包含lower和upper）之内的 区间和的个数 。
 * 区间和S(i, j)表示在nums中，位置从i到j的元素之和，包含i和j(i ≤ j)。
 * 示例 1：
 * 输入：nums = [-2,5,-1], lower = -2, upper = 2
 * 输出：3
 * 解释：存在三个区间：[0,0]、[2,2] 和 [0,2] ，对应的区间和(相加)分别是：-2 、-1 、2 。
 * 示例 2：
 * 输入：nums = [0], lower = 0, upper = 0
 * 输出：1
 * 提示：
 * 1 <= nums.length <= 105
 * -231 <= nums[i] <= 231 - 1
 * -105 <= lower <= upper <= 105
 * 题目数据保证答案是一个 32 位 的整数
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/count-of-range-sum
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class Solution_327 {

    public static void main(String[] args) {
        int[] arr = new int[]{19, -30, 46, -15, -5, -34, -8, 27, 48};
        //arr = new int[]{-2,5,-1};
        int lower = -9;
        //lower = -2;
        int upper = 9;
        //upper = 2;
        System.out.println("真实：" + countRangeSum(arr, lower, upper));
        System.out.println(Arrays.toString(arr));
    }

    public static int countRangeSum(int[] nums, int lower, int upper) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        // 防止相加越界，用long接收
        long[] sums = new long[nums.length];
        sums[0] = nums[0];
        for (int i = 1; i < nums.length; i++) {
            sums[i] = sums[i - 1] + nums[i];
        }
        return process(sums, 0, nums.length - 1, lower, upper);
    }

    private static int process(long[] sums, int L, int R, int lower, int upper) {
        if (L == R) {
            return (sums[L] >= lower && sums[L] <= upper) ? 1 : 0;
        }
        int M = L + ((R - L) >> 1);
        return process(sums, L, M, lower, upper) + process(sums, M + 1, R, lower, upper) + merge(sums, L, M, R, lower, upper);
    }

    private static int merge(long[] sums, int l, int m, int r, int lower, int upper) {
        int res = 0;
        int winL = l;
        int winR = l;
        /**
         * 重点
         */
        for (int i = m + 1; i <= r; i++) {
            double max = sums[i] - lower;
            double min = sums[i] - upper;
            while (winR <= m && sums[winR] <= max) {
                winR++;
            }
            while (winL <= m && sums[winL] < min) {
                winL++;
            }
            res += winR - winL;
        }

        int L1 = l;
        int R1 = m + 1;
        int curIndex = 0;
        long[] helper = new long[r - l + 1];
        while (L1 <= m && R1 <= r) {
            helper[curIndex++] = sums[L1] < sums[R1] ? sums[L1++] : sums[R1++];
        }
        while (L1 <= m) {
            helper[curIndex++] = sums[L1++];
        }
        while (R1 <= r) {
            helper[curIndex++] = sums[R1++];
        }
        for (int i = 0; i < helper.length; i++) {
            sums[l++] = helper[i];
        }
        return res;
    }


}
